/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package services;

import java.io.File;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;

/**
 *
 * @author ntfsbk
 */
public class XmlManager {

    private DocumentBuilderFactory docFactory;
    private DocumentBuilder docBuilder;
    private Document doc;
    private TransformerFactory transformerFactory;
    private Transformer transformer;
    private String pathName;
    private File dataFile;
    private String userId;
    private Element currentUserNode;

    public XmlManager(String PathName, String UserId) {
        try {
            docFactory = DocumentBuilderFactory.newInstance();
            docBuilder = docFactory.newDocumentBuilder();
            transformerFactory = TransformerFactory.newInstance();
            transformer = transformerFactory.newTransformer();
            this.pathName = PathName;
            this.userId = UserId;
            dataFile = new File(PathName);

            if (dataFile.exists() == false) {
                createXML();
            } else {
                readXML();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public XmlManager(String UserId) {
        try {
            docFactory = DocumentBuilderFactory.newInstance();
            docBuilder = docFactory.newDocumentBuilder();
            transformerFactory = TransformerFactory.newInstance();
            transformer = transformerFactory.newTransformer();

            this.pathName = UserId + ".xml";
            this.userId = UserId;
            dataFile = new File(pathName);

            if (dataFile.exists() == false) {
                createXML();
            } else {
                readXML();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean createXML() {
        try {
            doc = docBuilder.newDocument();
            Element rootElement = doc.createElement("tempdata");
            doc.appendChild(rootElement);

            currentUserNode = doc.createElement("user");
            currentUserNode.setAttribute("id", userId);
            rootElement.appendChild(currentUserNode);

            DOMSource source = new DOMSource(doc);

            StreamResult result = new StreamResult(dataFile);
            transformer.transform(source, result);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }

    public boolean readXML() {

        try {
            doc = docBuilder.parse(dataFile);
            Element tempdata = (Element) doc.getDocumentElement();
            NodeList userElements = tempdata.getChildNodes();

            int index = 0;
            boolean hasUser = false;
            for (int i = 0; i < userElements.getLength(); ++i) {
                Node userElement = userElements.item(i);
                NamedNodeMap attrs = userElement.getAttributes();
                Node attr = attrs.getNamedItem("id");
                String nameNode = attr.getNodeValue();
                if (nameNode.equalsIgnoreCase(userId)) {
                    index = i;
                    hasUser = true;
                    break;
                }
            }
            if (hasUser == true) {
                currentUserNode = (Element) userElements.item(index);
            } else {
                currentUserNode = doc.createElement("user");
                currentUserNode.setAttribute("id", userId);
                tempdata.appendChild(currentUserNode);

                DOMSource source = new DOMSource(doc);

                StreamResult result = new StreamResult(dataFile);
                transformer.transform(source, result);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    public void addNodeXML(MyFile myFile) {
        try {

            Element myfile = doc.createElement("myfile");
            currentUserNode.appendChild(myfile);

            Element fileid = doc.createElement("fileid");
            fileid.appendChild(doc.createTextNode(String.valueOf(myFile.getFileId())));
            myfile.appendChild(fileid);

            Element userid = doc.createElement("userid");
            userid.appendChild(doc.createTextNode(myFile.getUserId()));
            myfile.appendChild(userid);

            Element filename = doc.createElement("filename");
            filename.appendChild(doc.createTextNode(myFile.getFileName()));
            myfile.appendChild(filename);

            Element filesize = doc.createElement("filesize");
            filesize.appendChild(doc.createTextNode(String.valueOf(myFile.getFileSize())));
            myfile.appendChild(filesize);

            Element filedescriptiom = doc.createElement("filedescription");
            filedescriptiom.appendChild(doc.createTextNode(myFile.getFileDescription()));
            myfile.appendChild(filedescriptiom);

            Element iscomplete = doc.createElement("iscomplete");
            iscomplete.appendChild(doc.createTextNode(String.valueOf(myFile.isComplete())));
            myfile.appendChild(iscomplete);

            Element completedata = doc.createElement("completedata");
            completedata.appendChild(doc.createTextNode(String.valueOf(myFile.getCompleteData())));
            myfile.appendChild(completedata);

            Element pathname = doc.createElement("pathname");
            pathname.appendChild(doc.createTextNode(myFile.getPathName()));
            myfile.appendChild(pathname);

            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(dataFile);
            transformer.transform(source, result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void deleteFile(int FileId) {
        try {
            NodeList myFiles = currentUserNode.getChildNodes();
            int length = myFiles.getLength();
            int index = 0;
            for (int i = 0; i < length; ++i) {
                Node myFile = myFiles.item(i);
                String idString = myFile.getChildNodes().item(0).getFirstChild().getNodeValue();
                int id = Integer.valueOf(idString);
                if (id == FileId) {
                    index = i;
                    break;
                }
            }
            Node removeNode = myFiles.item(index);
            currentUserNode.removeChild(removeNode);

            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(dataFile);
            transformer.transform(source, result);
        } catch (Exception e) {
        }
    }

    public ArrayList<MyFile> scanMyFile() {

        ArrayList<MyFile> listInfo = new ArrayList<MyFile>();

        try {
            NodeList myfiles = currentUserNode.getChildNodes();

            int length1 = myfiles.getLength();
            for (int i = 0; i < length1; ++i) {
                MyFile tempFile = new MyFile();

                NodeList properties = myfiles.item(i).getChildNodes();

                int length2 = properties.getLength();
                for (int j = 0; j < length2; ++j) {
                    Node currentNode = properties.item(j);
                    String nameNode = currentNode.getNodeName();
                    if (nameNode.equalsIgnoreCase("fileid")) {
                        tempFile.setFileId(Integer.valueOf(currentNode.getFirstChild().getNodeValue()));
                    }
                    if (nameNode.equalsIgnoreCase("userid")) {
                        tempFile.setUserId(currentNode.getFirstChild().getNodeValue());
                    }
                    if (nameNode.equalsIgnoreCase("filename")) {
                        tempFile.setFileName(currentNode.getFirstChild().getNodeValue());
                    }
                    if (nameNode.equalsIgnoreCase("filesize")) {
                        tempFile.setFileSize(Float.valueOf(currentNode.getFirstChild().getNodeValue()));
                    }
                    if (nameNode.equalsIgnoreCase("filedescription")) {
                        tempFile.setFileDescription(currentNode.getFirstChild().getNodeValue());
                    }
                    if (nameNode.equalsIgnoreCase("iscomplete")) {
                        tempFile.setIsComplete(Boolean.valueOf(currentNode.getFirstChild().getNodeValue()));
                    }
                    if (nameNode.equalsIgnoreCase("completedata")) {
                        tempFile.setCompleteData(Float.valueOf(currentNode.getFirstChild().getNodeValue()));
                    }
                    if (nameNode.equalsIgnoreCase("pathname")) {
                        tempFile.setPathName(currentNode.getFirstChild().getNodeValue());
                    }
                }
                listInfo.add(tempFile);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return listInfo;
    }
    
        public void updateCompleteData(float completeData, int fileId){
        try {
            NodeList myFiles=currentUserNode.getChildNodes();
            int length=myFiles.getLength();
            int index=0;
            for(int i=0;i<length;++i){
                Node myFile=myFiles.item(i);
                String idString=myFile.getChildNodes().item(0).getFirstChild().getNodeValue();
                int id=Integer.valueOf(idString);
                if(id==fileId){
                    index=i;
                    break;
                }
            }
            Node currentFile=myFiles.item(index);
            Element oldElement=(Element)currentFile.getChildNodes().item(6);
            
            Element newElement = doc.createElement("completedata");
            newElement.appendChild(doc.createTextNode(String.valueOf(completeData)));
            currentFile.replaceChild(newElement, oldElement);
            
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(dataFile);
            transformer.transform(source, result);
        } catch (Exception e) {
            System.out.println("updateCompleteData");
            e.printStackTrace();
        }
        
    }
}
